/*
 * Filename: rgbctrl.c
 * Description: Parse config.txt file and apply device tree overlays
 *
 * Organization: lckfb
 * Author: Caicheng Wu
 * Email: 1378913492@qq.com
 * Date: 2024-08-30
 *
 * SPDX-License-Identifier:	GPL-2.0+
 */

#include <common.h>
#include <asm/gpio.h>

#define GPIO_RED 42
#define GPIO_GREEN 41
#define GPIO_BLUE 40

int rgb_ctrl(char led_char, const char *state_str) {
    int led;
    int state;

    switch (led_char) {
        case 'r':
            led = GPIO_RED;
            break;
        case 'g':
            led = GPIO_GREEN;
            break;
        case 'b':
            led = GPIO_BLUE;
            break;
        default:
            printf("Invalid LED character. Use 'r' for red, 'g' for green, 'b' for blue.\n");
            return CMD_RET_USAGE;
    }

    if (strcmp(state_str, "on") == 0) {
        state = 0;
    } else if (strcmp(state_str, "off") == 0) {
        state = 1;
    } else {
        printf("Invalid state. Use 'on' for on and 'off' for off.\n");
        return CMD_RET_USAGE;
    }

    if (gpio_request(led, "rgb-led") != 0) {
        printf("Failed to request GPIO %d. It might be already in use or not available.\n", led);
        return CMD_RET_FAILURE;
    }

    if (gpio_direction_output(led, state) != 0) {
        printf("Failed to set GPIO %d as output.\n", led);
        gpio_free(led);
        return CMD_RET_FAILURE;
    }

    gpio_set_value(led, state);
    printf("LED %c is now %s\n", led_char, state ? "on" : "off");

    gpio_free(led);

    return CMD_RET_SUCCESS;
}

int do_rgb_ctrl(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
{
    if (argc != 3) {
        return CMD_RET_USAGE;
    }

    return rgb_ctrl(argv[1][0], argv[2]);
}

U_BOOT_CMD(
    rgbctrl, 3, 1, do_rgb_ctrl,
    "Control LED state",
    "rgbctrl <led> <state>\n"
    "    - led: 'r' for red, 'g' for green, 'b' for blue\n"
    "    - state: 'on' to turn on, 'off' to turn off"
);